package Cn.Sarkar.Features

import io.ktor.application.ApplicationCallPipeline
import io.ktor.application.ApplicationFeature
import io.ktor.http.HttpStatusCode
import io.ktor.response.ApplicationSendPipeline
import io.ktor.util.AttributeKey
import java.io.PrintWriter
import java.io.StringWriter

object ExceptionPage : ApplicationFeature<ApplicationCallPipeline, Unit, Unit> {
    override val key: AttributeKey<Unit> by lazy { AttributeKey<Unit>("ExceptionPage") }

    override fun install(pipeline: ApplicationCallPipeline, configure: Unit.() -> Unit) {
        pipeline.sendPipeline.intercept(ApplicationSendPipeline.Before){
            if (context.response.status() == null && subject is Exception) {

                val result = StringWriter()
                val writer = PrintWriter(result)
//                (subject as Exception).printStackTrace(writer)
                writer.flush()
                result.flush()
                val excepMessage = result.toString()

                context.response.status(HttpStatusCode.InternalServerError)
            }
        }
    }
}